/**
 * 使用组件的方式构建表单
 */
 import { Formik, Form, Field, ErrorMessage, useField } from "formik";
 import * as Yup from "yup";
 
 // 自定义表单控件
 function MyInput({ label, ...props }) {
   const [field, meta, helper] = useField(props);
   const { value } = meta;
   const { setValue } = helper;
   const handleChange = e => {
     console.log('自定义表单控件==>', value)
    //  console.log('自定义表单控件', props)
     setValue(e.target.value);
   };
   return (
     <div>
       <label htmlFor={props.id}>{label}</label>
       <input {...field} {...props}  onChange={handleChange}/>
       {meta.touched && meta.error ? <span>{meta.error}</span> : null}
     </div>
   );
 }
 
 function Checkbox({ label, ...props }) {
   const [field, meta, helper] = useField(props);
   const { value } = meta;
   const { setValue } = helper;
   const handleChange = () => {
     const set = new Set(value);
     if (set.has(props.value)) {
       set.delete(props.value);
     } else {
       set.add(props.value);
     }
     setValue([...set]);
   };
   return (
     <div>
       <label>
         <input checked={value.includes(props.value)} type="checkbox" {...props} onChange={handleChange} />
         {label}
       </label>
     </div>
   );
 }
 
 function App() {
   const initialValues = {
     username: "",
     content: "文本域",
     subject: "前端",
     hobbies: ['足球'],
   };
   const handleSubmit = (values) => {
     console.log("提交表单", values);
   };
   const schema = Yup.object({
     username: Yup.string()
       .max(15, "用户名的长度不能大于15")
       .required("请输入用户名"),
     password: Yup.string().min(6, "密码长度不能小于6").required("请输入密码"),
   });
   return (
     <Formik
       initialValues={initialValues}
       validationSchema={schema}
       onSubmit={handleSubmit}
     >
       <Form>
         <Field name="username" />
         <ErrorMessage name="username" />
         <Field as="textarea" name="content" />
         <Field as="select" name="subject">
           <option value="前端">前端</option>
           <option value="Java">Java</option>
         </Field>
         <MyInput
           label="密码"
           name="password"
           type="password"
           id="mypass"
           placeholder="请输入密码"
         />
         <Checkbox label="足球" value="足球" name="hobbies" />
         <Checkbox label="羽毛球" value="羽毛球" name="hobbies" />
         <Checkbox label="篮球" value="篮球" name="hobbies" />
         <input type="submit" />
       </Form>
     </Formik>
   );
 }
 
 export default App;
 